<template>
    <n-modal id="basic-modal" v-model:show="visible" @on-update:show="cb">
        <n-card v-bind="mergedProps" @close="closeModal">
            <template #header>
                <slot name="header"> {{ mergedTitle }}</slot>
            </template>
            <slot></slot>
            <template #footer>
                <slot name="footer">
                    <GetanButtonGroup :options="defaultActions" justify="end" />
                </slot>
            </template>
        </n-card>
    </n-modal>
</template>

<script lang="ts" setup>
import { isEmpty } from "@/utils"
import { useActions } from "./hooks/useActions"
import { GetanModalProps, ModalMethods } from "./types"
import { GetanButtonGroup } from "@/components/ButtonGroup"

const attrs = useAttrs()
const props = defineProps<{ options?: GetanModalProps }>()
const propsRef = ref<Partial<GetanModalProps>>({})

const titleRef = ref<string>("")
const mergedTitle = computed(() => (isEmpty(titleRef.value) ? unref(mergedOptions).title : unref(titleRef)))

const mergedOptions = computed(() => {
    return {
        ...props.options,
        ...unref(propsRef)
    }
})

const defaultProps = {
    bordered: true,
    headerStyle: { padding: "8px 15px", borderBottom: "1px solid var(--n-border-color)" },
    footerStyle: { padding: "10px 15px", borderTop: "1px solid var(--n-border-color)" },
    contentStyle: { paddingBottom: 0 }
}

function parseProps(options: Ref<GetanModalProps>) {
    return {
        closable: unref(options).closable ?? true,
        style: { width: unref(options).width ? `${unref(options).width}px` : "600px" }
    }
}

const mergedProps = computed(() => {
    return {
        ...defaultProps,
        ...attrs,
        ...(isEmpty(unref(mergedOptions)) ? {} : parseProps(mergedOptions))
    }
})

const emits = defineEmits(["on-close", "on-ok", "on-cancel", "register"])
const visible = ref<boolean>(false)
const { defaultActions } = useActions(mergedOptions, visible, emits)

function openModal(title?: string) {
    title && (titleRef.value = title)
    visible.value = true
    nextTick(() => {
        // const oBox = document.getElementById("basic-modal")
        // const oBar = document.getElementById("basic-modal-bar")
        // startDrag(oBar, oBox)
    })
}

function closeModal() {
    visible.value = false
}

function init(registerProps: Partial<GetanModalProps>) {
    propsRef.value = registerProps ?? {}
}

/**
 * 关闭后回调
 */
function cb() {
    console.log("execute cb")

    emits("on-close")
}

const modalMethods: ModalMethods = {
    init,
    open: openModal,
    close: closeModal
}

const instance = getCurrentInstance()
if (instance) {
    emits("register", modalMethods)
}
</script>

<style lang="less">
.cursor-move {
    cursor: move;
}
</style>
